package org.goodsl.mdd.validator;

import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
import org.goodsl.mdd.Seg;


import org.goodsl.mdd.SingleValidResult;

import org.goodsl.mdd.Validator;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 * User: Simon Xiao
 * Date: 12-11-13
 * Time: 下午2:56
 * To change this template use File | Settings | File Templates.
 */
public class SizeValidator extends Validator<Seg> {

    private static final String[] methods = {"length","size"};
    private static final String[] fields = {"length"};

    public int min;
   	public int max;

    public SizeValidator(int min,int max,String message){
        super(message);
        this.min = min;
        this.max = max;
    }

    @Override
    public SingleValidResult<Seg> verify(Seg variable) {
        Object valueObject = variable.getValue();
        Class<?> valueClass = valueObject.getClass();
        int length = -1 ;
        boolean got = false;
        for(String methodName : methods){
            try{

                Method method =valueClass.getMethod(methodName, new Class[]{});
                if(method!=null){
                   length = DefaultTypeTransformation.castToNumber(method.invoke(valueObject,new Object[]{})).intValue();
                }
                //length = valueObject."$methodName"();
                got = true;
            }catch(Exception e){}
            if(got)
                break;
        }

        if(!got){
            for(String fieldName : fields){
                try{
                    Field field = valueClass.getField(fieldName);
                    if(field!=null){
                        length = DefaultTypeTransformation.castToNumber(field.get(valueObject)).intValue();
                    }
                    //length = valueObject."$fieldName";
                    got = true;
                }catch(Exception e){}
                if(got)
                    break;
            }
        }

        if(got && length>=min && length <= max)
            return new SingleValidResult<Seg>(true,"",variable,this);
        else
            return new SingleValidResult<Seg>(false,getMessage(),variable,this);
    }
}
